<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2018-06-14
 * Time: 16:58
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\Prize as PrizeModel;
use app\api\model\User as UserModel;
use app\api\validate\CheckLuckRecord;
use app\api\service\Token as TokenService;
use app\api\model\LuckRecord as LuckRecordModel;
use app\lib\exception\MissException;
use app\lib\exception\SuccessMessage;
use app\lib\exception\UserException;
use think\Db;
use think\Exception;

class LuckRecord extends BaseController
{
    // 保存用户抽奖的中奖信息
    public function saveLuckRecord(){
        $validate = new CheckLuckRecord();
        $validate->goCheck();
        $uid = TokenService::getCurrentUid();
        if(!$uid){
            throw new UserException();
        }
        $luckRecordInfo = $validate->getDataByRule(input('post.'));
        if(!empty($luckRecordInfo) && array_key_exists('prize_id', $luckRecordInfo)){
            $activityId = $luckRecordInfo['active_id'];
            $prizeName = $luckRecordInfo['prize_name'];
            $prize_id = $luckRecordInfo['prize_id'];
            $prize_img = $luckRecordInfo['prize_img'];
            Db::startTrans();
            try{
                $luckRecord = LuckRecordModel::where('userId', '=' , $uid)->where('activityId', '=', $activityId)->find();
                $prizeInfo = PrizeModel::get($prize_id);
                $userInfo = UserModel::get($uid);
                if(empty($luckRecord) && $prizeInfo->remainNum > 0){
                    $luck = new LuckRecordModel();
                    $luck->userId = $uid;
                    $luck->activityId = $activityId;
                    $luck->prizeId = $prizeName;
                    $luck->prizeImg = $prize_img;
                    $luck->name = $userInfo->nickname;
                    $luck->save();
                    $prizeInfo->remainNum = $prizeInfo->remainNum - 1;
                    $prizeInfo->save();
                    Db::commit();
                }else{
                    return json(new SuccessMessage([
                        'code' => 201,
                        'msg' => '用户已中奖，同一活动只能中奖一次，或该奖品全部发放剩余0件'
                    ]),201);
                }
            }catch (Exception $exception){
                Db::rollback();
                throw $exception;
            }
        }else{
            throw new MissException([
                'msg' => '中奖信息不存在，禁止写入数据库',
                'errorCode' => 40010
            ]);
        }
        return json(new SuccessMessage([
            'code' => 200,
            'msg' => '用户中奖信息写入数据库成功'
        ]),200);
    }

    // 获取某用户的所有中奖信息，在个人中心-我的奖品显示
    public function getMyluckRecords(){
        $uid = TokenService::getCurrentUid();
        $luckRecord = LuckRecordModel::with(['actives'])->where('userId','=',$uid)->select()->toArray();
        return [
            'data' => $luckRecord
        ];
    }

    // 更新中奖记录中的用户微信名
    public function updateLuckRecordName(){
        Db::startTrans();
        try{
            $luckInfo = LuckRecordModel::all()->toArray();
            foreach ($luckInfo as $luck){
                $userInfo = UserModel::where('id','=',$luck['userId'])->find();
                $luck_record = LuckRecordModel::get($luck['id']);
                $luck_record->name = $userInfo->nickname;
                $luck_record->save();
            }
            Db::commit();
            return json(new SuccessMessage([
                'code' => 200,
                'msg' => '中奖用户微信名称写入中奖记录成功'
            ]),200);
        }catch (Exception $exception){
            Db::rollback();
            throw $exception;
        }
    }

}